package com.zhiyin.seal.controller;

import com.zhiyin.seal.entity.bo.ApplyAttachmentBo;
import com.zhiyin.seal.entity.bo.ImageBo;
import com.zhiyin.seal.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * 文件业务控制器
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileService fileService;

    @Value("${myconfig.image-path}")
    private String imagePath;

    @Value("${myconfig.domain}")
    private String domain;

    @Value("${myconfig.downloadimage}")
    private String downloadimage;

    @Value("${myconfig.attachment-path}")
    private String attachmentPath;

    /**
     * 图片上传
     * @param userId
     * @param file
     * @return
     */
    @RequestMapping(value = "/uploadimage",method= RequestMethod.POST)
    public String uploadImage(@RequestParam Long userId, @RequestParam("file") MultipartFile file) {
        ImageBo imageBo = new ImageBo();
        imageBo.setCreateUser(userId);
        imageBo.setImagePath(imagePath);
        String imageName =  fileService.uploadImage(imageBo,file);

        if(imageName != null){
            return domain + downloadimage + "?imageName=" + imageName;
        }

        return null;
    }

    /**
     * 图片下载
     * @param imageName
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/downloadimage")
    public void downloadImage(@RequestParam String imageName, HttpServletResponse response) throws IOException{
        FileSystemResource file = fileService.downloadImage(imageName);
        if(file != null) {
            // 读取文件
            InputStream inputStream =file.getInputStream();
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            inputStream.close();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            response.setContentType("image/jpeg");
            response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(file.getFilename(), "UTF-8"));
            response.addHeader("Content-Length", "" + buffer.length);
            // 写入响应流
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            outputStream.write(buffer);
            outputStream.flush();
            outputStream.close();
        }
    }

    /**
     * pdf文件下载
     * @param fileName
     * @param companyId
     * @param type
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/downloadpdf")
    public void downloadPdf(@RequestParam String fileName,@RequestParam Long companyId,@RequestParam Integer type,HttpServletResponse response) throws IOException{
        FileSystemResource file = fileService.downloadPdf(fileName,companyId,type);
        if(file != null) {
            // 读取文件
            InputStream inputStream =file.getInputStream();
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            inputStream.close();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/pdf");
            response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(file.getFilename(), "UTF-8"));
            response.addHeader("Content-Length", "" + buffer.length);
            // 写入响应流
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            outputStream.write(buffer);
            outputStream.flush();
            outputStream.close();
        }
    }

    @RequestMapping(value = "/attachment/upload",method= RequestMethod.POST)
    public String uploadAttachment(@RequestParam Long userId, @RequestParam("file") MultipartFile file){
        ApplyAttachmentBo attachmentBo = new ApplyAttachmentBo();
        attachmentBo.setCreateUser(userId);
        attachmentBo.setFilePath(attachmentPath);
        Boolean result =fileService.uploadAttachment(attachmentBo,file);
        if(result){
            return attachmentBo.getFileUrl();
        }

        return null;
    }

    @RequestMapping(value = "/attachment/download")
    public void downloadAttachment(@RequestParam String fileName,HttpServletResponse response) throws IOException{
        ApplyAttachmentBo attachmentBo = fileService.getAttachmentByFileName(fileName);
        if(attachmentBo == null){
            return;
        }
        // 读取文件
        FileSystemResource file = fileService.downloadAttachment(fileName);
        InputStream inputStream =file.getInputStream();
        byte[] buffer = new byte[inputStream.available()];
        inputStream.read(buffer);
        inputStream.close();
        // 设置response的Header
        response.setCharacterEncoding("UTF-8");
        response.setContentType(attachmentBo.getMimeType());
        response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(attachmentBo.getOriginalName(), "UTF-8"));
        response.addHeader("Content-Length", "" + buffer.length);
        // 写入响应流
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        outputStream.write(buffer);
        outputStream.flush();
        outputStream.close();
    }
}
